import requests
import pymongo
from config.configs import ALPHA_DB_HOST, ALPHA_DB_PORT, GOAT_ERP_HOST, GOAT_ERP_PORT
from tools.funciton import *

alpha = pymongo.MongoClient(ALPHA_DB_HOST, ALPHA_DB_PORT).alpha
jiwu = pymongo.MongoClient(ALPHA_DB_HOST, ALPHA_DB_PORT).jiwu
file = os.path.join(DATA_PATH, 'add_spu_datas.json')


def jiwu_token():
    """登录集物后台获取token"""
    url = 'https://erp.geehoop.com/api/backend/auth/login'
    param = {
        "mobile": "17313699441",
        "password": "17313699441"
    }
    res = requests.post(url=url, json=param)
    token = res.json()['data']['token']
    return {'Authorization': f'Bearer {token}'}


def alpha_update_spu_sku(articleNumber):
    """集物更新货号"""
    url = f'https://erp.geehoop.com/api/backend/spu/query/{articleNumber}'
    header = jiwu_token()
    if jiwu.spus.count_documents({'articleNumber': articleNumber}) == 1:
        print(jiwu.spus.count_documents({'articleNumber': articleNumber}))
        spu = [i['spuId'] for i in jiwu.spus.find({'articleNumber': articleNumber})][0]
        jiwu.skus.delete_many({'spuId': spu})
        jiwu.spus.delete_one({'spuId': spu})
        requests.get(url=url, headers=header)
    else:
        requests.get(url=url, headers=header)


def jiwu_insert_spu_api():
    """新增货号尺码-（直接通过得物api查询数据）"""
    res = read_json_file(file)['data']
    for i in range(len(res)):
        if '定制球鞋' in res[i]['title']:
            pass
        else:
            spuId = read_json_file(file)['data'][i]['spu_id']
            jiwu.spus.delete_one({'spuId': spuId})
            jiwu.skus.delete_many({'spuId': spuId})
            spu_datas = read_json_file(file)['data'][i]
            sku_datas = read_json_file(file)['data'][i]['skus']
            spu_param = {'spuId': spuId,
                         'title': spu_datas['title'],
                         'brandId': spu_datas['brand_id'],
                         'brandName': spu_datas['brand_name'],
                         'categoryId': spu_datas['category_id'],
                         'categoryName': spu_datas['category_name'],
                         'articleNumber': spu_datas['article_number'],
                         'otherNumbers': spu_datas['other_numbers'],
                         'spuLogo': spu_datas['spu_logo'],
                         'authPrice': spu_datas['auth_price'] / 100,
                         'supportCross': spu_datas['support_cross'],
                         'createdAt': int(round(time.time() * 1000)),
                         'updatedAt': int(round(time.time() * 1000)),
                         "status": 1}
            jiwu.spus.insert_one(spu_param)
            for z in range(len(sku_datas)):
                items = json.loads(sku_datas[z]['properties'])
                sku_param = {"spuId": spuId, "skuId": sku_datas[z]['sku_id'],
                             "properties": json.dumps(items, ensure_ascii=False).replace(" ", ""),
                             'barcode': sku_datas[z]['barcode'],
                             'status': 1,
                             "__v": 0, "createdAt": int(round(time.time() * 1000)),
                             "updatedAt": int(round(time.time() * 1000))}
                jiwu.skus.insert_one(sku_param)


jiwu_insert_spu_api()
# alpha_update_spu_sku('HQ6025-001')
